package com.ysg.widget.tree;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public abstract class AbsTreeAdapter extends BaseAdapter {
    protected Context mContext;
    protected List<Node> mAllNodes = new ArrayList<>(), mNodes = new ArrayList<>();
    protected LayoutInflater mInflater;
    private OnTreeNodeClickListener onTreeNodeClickListener;

    public interface OnTreeNodeClickListener {
        void onClick(Node node, int position);
    }

    public void setOnTreeNodeClickListener(OnTreeNodeClickListener onTreeNodeClickListener) {
        this.onTreeNodeClickListener = onTreeNodeClickListener;
    }

    /**
     * defaultExpandLevel 默认展开几级树
     */
    public AbsTreeAdapter(ListView mTree, Context context, List<Node> trees, int defaultExpandLevel){
        try {
            mContext = context;
            mAllNodes = TreeHelper.getSortedNodes(trees, defaultExpandLevel);
            mNodes = TreeHelper.filterVisibleNode(mAllNodes);
            mInflater = LayoutInflater.from(context);
        }catch (Exception e){
        }

        mTree.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                expandOrCollapse(position);
                if (onTreeNodeClickListener != null) {
                    onTreeNodeClickListener.onClick(mNodes.get(position),position);
                }
            }
        });
    }

    /**
     * 相应ListView的点击事件
     */
    public void expandOrCollapse(int position) {
        Node n = mNodes.get(position);
        if (n != null){
            if (!n.isLeaf()) {
                n.setExpand(!n.isExpand());
                mNodes = TreeHelper.filterVisibleNode(mAllNodes);
                notifyDataSetChanged();// 刷新视图
            }
        }
    }

    @Override
    public int getCount() {
        return mNodes.size();
    }

    @Override
    public Object getItem(int position) {
        return mNodes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Node node = mNodes.get(position);
        convertView = getConvertView(node, position, convertView, parent);
        convertView.setPadding(node.getLevel() * 20, 0, 5, 0);
        return convertView;
    }

    public abstract View getConvertView(Node node, int position, View convertView, ViewGroup parent);
}
